﻿using Innoapps.FileTransfer.Models;
using System;
using System.IO;
using System.Xml.Serialization;

namespace Innoapps.FileTransfer.Adapters.Receive
{
    public class FILE : Base
    {

        #region Properties

        [XmlAttribute("uri")]
        public override string uri
        {
            get
            {
                return Path.Combine(FolderPath, FileName);
            }
            set
            {
                Uri u = new Uri(value);

                FolderPath = Path.GetDirectoryName(u.LocalPath);
                FileName = Path.GetFileName(u.LocalPath);

            }
        }

        [XmlAttribute("DeleteAfterTransfer")]
        public bool DeleteAfterTransfer { get; set; }

        [XmlAttribute("FolderPath")]
        public string FolderPath { get; set; }
        [XmlAttribute("FileName")]
        public string FileName { get; set; }

        [XmlAttribute("TemporaryFolder")]
        public string TemporaryFolder { get; set; }

        #endregion

        #region Methods

        public override void Receive()
        {
            try {

                FileStream stream;

                if (TemporaryFolder != "")
                {
                    File.Move(Path.Combine(FolderPath, FileName), Path.Combine(TemporaryFolder, transfer.Id + ".tmp"));
                    stream = new FileStream(Path.Combine(TemporaryFolder, transfer.Id + ".tmp"), FileMode.Open, FileAccess.Read);
                    
                }
                else
                {
                    stream = new FileStream(Path.Combine(FolderPath, FileName), FileMode.Open, FileAccess.Read);
                }
                transfer.Stream = stream;
                Pass();
            } catch(Exception e)
            {
                Fail(e.Message);
            }
        }

        public override void Delete()
        {
            try
            {
                if (DeleteAfterTransfer)
                {
                    if (TemporaryFolder != "")
                    {
                        File.Delete(Path.Combine(TemporaryFolder, transfer.Id + ".tmp"));
                    }
                    else
                    {
                        System.IO.File.Delete(Path.Combine(FolderPath, FileName));
                    }
                    Pass();
                } else
                {
                    Pass();
                }
            }
            catch (Exception e)
            {
                Fail(e.Message);
            }
        }

        #endregion

    }
}
